package sh.grapendaal.tsuushin.module;

import sh.grapendaal.tsuushin.service.PermissionService;

import com.google.inject.AbstractModule;
import com.google.inject.ConfigurationException;
import com.google.inject.Guice;
import com.google.inject.Inject;
import com.google.inject.Injector;

public class ModuleServiceProxyFactory extends AbstractModule {

	@Inject
	private Injector mainInjector;

	private static Injector moduleInjector = Guice.createInjector(new ModuleServiceProxyFactory());

	/**
	 * This method configures the available module service proxies.
	 */
	@Override
	protected void configure() {
		bind(PermissionService.class).to(PermissionModuleServiceProxy.class);
	}

	/**
	 * Creates a proxy for a module for the given type. The given type should be
	 * configured in either the module injector or the main injector. If the
	 * type could not be found in the module injector, this method will return
	 * the normal instance of the type from the main injector.
	 * 
	 * @param type
	 *            The class to proxy.
	 * @return The module specific proxy.
	 */
	public <T> T create(Class<T> type) {
		T proxy = null;
		try {
			proxy = moduleInjector.getInstance(type);
			// Inject references to the normal service instances.
			mainInjector.injectMembers(proxy);
		} catch (ConfigurationException e) {
			proxy = mainInjector.getInstance(type);
		}

		return proxy;
	}
}
